<template>
  <div class="header">
    <div class="logo-wrapper" :class="{'is-collapse': $store.state.isCollapse}" @click="goHome">
      <div><img class="logo" src="../assets/images/logo.png" width="115" height="58"></div>
    </div>
    <div class="menu-wrapper" :class="{'is-collapse': $store.state.isCollapse}">
      <div class="slide-btn" @click="toggleSlide">
        <img class="icon-menu" src="../assets/images/icon-menu.png" width="27" height="20">
      </div>
      <el-menu class="menu" mode="horizontal" ref="menu" :default-active="cpath">
        <el-menu-item index='/home' @click="goHome">首页</el-menu-item>
        <el-menu-item v-for="(item, index) in list" :key="index" :index="item.path" @click="setMenu(item.path)">{{item.name}}</el-menu-item>
      </el-menu>
    </div>
    <div class="user-wrapper">
      <!-- 个人信息 -->
      <el-dropdown class="userinfo-dropdown" @command="executeCommand">
        <span>
          <i class="iconfont icon-avatar"></i>
          <span v-if="name" class="username">{{name}}</span>
          <span v-else>用户</span>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="editPassword">
            <i class="iconfont icon-lock"></i>
            修改密码
          </el-dropdown-item>
          <el-dropdown-item command="exit">
            <i class="iconfont icon-logout"></i>
            退出登录
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <!-- 返回首页 -->
      <router-link class="tool-item" :to="{path: '/home'}"><i class="iconfont icon-home"></i></router-link>
    </div>
    <!-- 修改密码 -->
    <el-dialog title="修改密码" :visible.sync="passwordDialog" :modal-append-to-body="false">
      <el-form :model="passwordForm" ref="passwordForm" :rules="rules" label-width="150px">
        <el-form-item label="请输入旧密码" prop="oldPassword">
          <el-input type="password" :minlength="6" :maxlength="20" v-model="passwordForm.oldPassword"></el-input>
        </el-form-item>
        <el-form-item label="请输入新密码" prop="newPassword">
          <el-input type="password" :minlength="6" :maxlength="20" v-model="passwordForm.newPassword"></el-input>
        </el-form-item>
        <el-form-item label="请再次输入新密码" prop="confirmPassword">
          <el-input type="password" :minlength="6" :maxlength="20" v-model="passwordForm.confirmPassword"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="savePassword">保存</el-button>
        <el-button type="default" @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MD5 from 'js-md5'
import { mapState, mapMutations, mapActions } from 'vuex'
export default {
  props: ['cpath'],
  data () {
    return {
      activeIndex: 1,
      passwordDialog: false, // 修改密码窗口
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value.length < 6) {
                callback(new Error('密码限制6-20个字'))
              } else if (value.length > 60) {
                callback(new Error('密码限制6-20个字'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        confirmPassword: [
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请再次输入新密码'))
              } else if (value !== this.passwordForm.newPassword) {
                callback(new Error('两次输入的密码不一致'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    ...mapState({
      name: state => state.user.name,
      list: state => state.permission
    })
  },
  methods: {
    // 收缩/展开侧边栏
    toggleSlide () {
      this.setCollapse(!this.$store.state.isCollapse)
    },
    ...mapMutations({
      setCPath: 'setCPath',
      setCollapse: 'setCollapse'
    }),
    ...mapActions({
      getPermission: 'getPermission',
      logout: 'logout'
    }),
    // 设置选中的菜单模块
    setMenu (data) {
      this.setCPath(data)
    },
    // 执行方法（command）
    executeCommand (command) {
      if (command) {
        this[command]()
      } else {
        return false
      }
    },
    // 返回首页
    goHome () {
      this.setMenu('')
      this.$router.push('/home')
    },
    // 退出登录
    exit () {
      this.$confirm('是否退出当前账户？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.logout()
      }).catch(() => {
        this.$message('已取消退出')
      })
    },
    // 修改密码
    editPassword () {
      this.passwordDialog = true
      this.$nextTick(() => {
        this.$refs.passwordForm.resetFields()
      })
    },
    // 保存修改密码
    savePassword () {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.$http.post(this.$api + '/user/modifyPsw', {
            oldPsw: MD5(this.passwordForm.oldPassword),
            newPsw: MD5(this.passwordForm.newPassword)
          }).then(res => {
            if (res.responseCode === '0000') {
              this.$message({
                type: 'success',
                message: '修改密码成功，请重新登录！',
                duration: this.$store.state.duration,
                onClose: () => {
                  this.$router.push('/login')
                }
              })
            } else {
              this.$message.error({
                message: res.responseMsg,
                duration: this.$store.state.duration,
                onClose: () => {
                  this.passwordForm.newPassword = ''
                  this.passwordForm.confirmPassword = ''
                  this.passwordForm.oldPassword = ''
                }
              })
            }
          }).catch(err => {
            console.error(err)
          })
        } else {
          return false
        }
      })
    },
    // 取消修改密码
    cancel () {
      this.passwordDialog = false
    }
  },
  watch: {
    'cpath': function (val) {
      this.$refs.menu.activeIndex = val
    }
  }
}
</script>

<style lang="scss">
  .header{
    position: relative;
    z-index: 1000;
    height: 80px;
    background: #fff;
    box-shadow: 0 2px 8px rgba(173, 184, 195, 0.35);
    .logo-wrapper{
      position: absolute;
      top: 0;
      left: 0;
      width: 240px;
      height: 100%;
      transition: all 0.3s;
      cursor: pointer;
      &::after{
        content: '';
        position: absolute;
        top: 50%;
        right: 0;
        margin-top: -16px;
        width: 1px;
        height: 32px;
        background: #f2f2f2;
      }
      &.is-collapse{
        width: 80px;
        &::after{
          display: none;
        }
        .logo{
          transform: scale(0.7) translateX(15px);
        }
      }
      .logo{
        display: block;
        margin: 10px auto;
        transform-origin: left;
        transition: all 0.1s ease-in-out;
      }
    }
    .menu-wrapper{
      margin-left: 240px;
      margin-right: 200px;
      font-size: 0;
      transition: all 0.3s;
      height: 80px;
      overflow: hidden;
      white-space: nowrap;
      &.is-collapse{
        margin-left: 80px;
      }
      .slide-btn{
        display: inline-block;
        vertical-align: top;
        padding: 30px 24px;
        cursor: pointer;
      }
      .menu{
        display: inline-block;
        border-bottom: 0;
        .el-menu-item{
          padding: 0 16px;
          height: 80px;
          line-height: 80px;
          color: #666;
          font-size: 16px;
          &.is-active{
            position: relative;
            color: #51ad81;
            background: #ebf0ed;
            border-bottom: 0;
            &::after{
              content: '';
              position: absolute;
              bottom: 0;
              left: 50%;
              margin-left: -22px;
              width: 44px;
              height: 6px;
              background: linear-gradient(left,#84c225,#44916c)!important;
              background: -webkit-gradient(linear, left top, right top, from(#84c225), to(#44916c))!important;
              background: -moz-linear-gradient(linear, left top, right top, from(#84c225), to(#44916c))!important;
            }
          }
        }
      }
    }
    .user-wrapper{
      position: absolute;
      top: 0;
      right: 0;
      text-align: right;
      box-sizing: border-box;
      padding-right: 10px;
      width: 200px;
      height: 80px;
      font-size: 0;
      .userinfo-dropdown{
        display: inline-block;
        vertical-align: top;
        margin-right: 10px;
        height: 80px;
        line-height: 80px;
        cursor: pointer;
        .iconfont{
          vertical-align: middle;
          font-size: 40px;
        }
        .username{
          display: inline-block;
          max-width: 70px;
          vertical-align: middle;
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .system-info{
        .el-badge{
          margin: 0 15px;
          .iconfont{
            font-size: 22px;
          }
        }
      }
      .tool-item{
        display: inline-block;
        padding: 0 15px;
        height: 80px;
        line-height: 80px;
        text-decoration: none;
        color: #666;
        cursor: pointer;
        .iconfont{
          font-size: 22px;
        }
      }
    }
  }
  .message-line{
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 150px;
    .num{
      i{
        font-style: normal;
        padding: 0 2px;
        color: #f00;
      }
    }
  }
</style>
